/*
 * Copyright (C) 2014 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */

package com.xierong.remoteplayerlauncher;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.DhcpInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;

import com.xierong.remoteplayerlauncher.model.PlayListItem;
import com.xierong.remoteplayerlauncher.recevier.ExternalStorageReceiver;
import com.xierong.remoteplayerlauncher.recevier.ExternalStorageReceiverHelper;
import com.xierong.remoteplayerlauncher.recevier.ExternalStorageReceiverHelper.ExternalStorageCommand;
import com.xierong.remoteplayerlauncher.utils.PlayerManager;

import java.io.File;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.ArrayList;

public class MainActivity extends Activity implements ExternalStorageCommand {
    private static final String BROADCAST_ADDR = "255.255.255.255";
    private ProgressDialog loadingDialog;
    private ExternalStorageReceiverHelper externalStorageReceiverHelper = null;
    private final static int READ_EXTERNAL_STORAGE_PERMMISSION_RESULT = 0;
    private TextView textView = null;
    private boolean isStarting = false;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_main);
        textView = findViewById(R.id.textField);
        checkReadExternalStoragePermission();
        listenExternalStorageEvents();
        Log.d(PlayerManager.TAG, "程序已经启动");
        new Thread(new Runnable() {
            @Override
            public void run() {
                sendFindHostMessage();
            }
        }).start();
    }

    private void sendFindHostMessage() {
        String message = "findHost";
        DatagramSocket sendSocket = null;
        try {
            sendSocket = new DatagramSocket();
            sendSocket.setBroadcast(true);
            DatagramPacket data = new DatagramPacket(message.getBytes(), message.length(), getBroadcastAddress(), 3321);
            sendSocket.send(data);
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
    InetAddress getBroadcastAddress() throws IOException {
        WifiManager wifi = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        DhcpInfo dhcp = wifi.getDhcpInfo();
        // handle null somehow

        int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask;
        byte[] quads = new byte[4];
        for (int k = 0; k < 4; k++)
            quads[k] = (byte) ((broadcast >> k * 8) & 0xFF);
        return InetAddress.getByAddress(quads);
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(externalStorageReceiverHelper);
        super.onDestroy();
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch(requestCode) {
            case READ_EXTERNAL_STORAGE_PERMMISSION_RESULT:
                if(grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //Call cursor loader
                    startPlayList();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    private void startPlayList() {
        if (this.isStarting) {
            return;
        }
        this.isStarting = true;
        String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + "/" + "playlist.xml";
        File file = new File(path);
        if (file.exists()) {
            Log.d(PlayerManager.TAG, "在下载目录中发现播放列表，开始播放");
            ArrayList<PlayListItem> list = PlayerManager.getInstance().pathToPlaylist(path);
            PlayerManager.getInstance().setPlaylist(list);
            Intent intent = new Intent(MainActivity.this, VideoActivity.class);
            startActivity(intent);
            this.finish();
        } else {
            textView.setText("暂无可播放的内容，请插入带有播放列表的外部存储进行更新");
        }
    }

    private void listenExternalStorageEvents() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ExternalStorageReceiver.EXTERNAL_STORAGE_CONFIG_PATH);
        intentFilter.addAction(ExternalStorageReceiver.EXTERNAL_STORAGE_NO_CONFIG);
        intentFilter.addAction(ExternalStorageReceiver.EXTERNAL_STORAGE_UNMOUNTED);
        externalStorageReceiverHelper = new ExternalStorageReceiverHelper();
        externalStorageReceiverHelper.setCommand(this);
        registerReceiver(externalStorageReceiverHelper, intentFilter);
    }

    private void checkReadExternalStoragePermission() {
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if(ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) ==
                    PackageManager.PERMISSION_GRANTED) {
                // Start cursor loader
                Log.d(PlayerManager.TAG, "已经获取了外部存储的权限");
                startPlayList();
            } else {
                if(shouldShowRequestPermissionRationale(Manifest.permission.READ_EXTERNAL_STORAGE)) {
                    Toast.makeText(this, "需要获得读取外部存储的权限才可以更新播放列表", Toast.LENGTH_SHORT).show();
                }
                requestPermissions(new String[] {Manifest.permission.READ_EXTERNAL_STORAGE},
                        READ_EXTERNAL_STORAGE_PERMMISSION_RESULT);
            }
        }
    }
    private void showLoading() {
        loadingDialog = ProgressDialog.show(MainActivity.this, "", "加载中，请稍后……", true);
    }
    private void hideLoading() {
        if (loadingDialog != null) {
            loadingDialog.cancel();
        }
    }

    @Override
    public void processConfig(String path) {
        Log.d(PlayerManager.TAG, "主界面提示刚刚插入U盘中发现播放列表：" + path);
        Intent intent = new Intent(MainActivity.this, FileCopyActivity.class);
        intent.putExtra("path", path);
        startActivity(intent);
        this.finish();
    }

    @Override
    public void noConfig() {
        Log.d(PlayerManager.TAG, "主界面提示，没有找到播放列表");
    }

    @Override
    public void externalStorageUnmounted() {
        Log.d(PlayerManager.TAG, "主界面提示：外部存储已经拔出");
    }
}
